package com.datasure.demo.webSocket.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

/**
 * @author xiaolong5.zhang
 * @date 2022/05/24 11:52
 **/
@WebListener
public class WebSocketListener implements ServletContextListener {

    @Autowired
    private WebSocketChildChannelHandler webSocketChildChannelHandler;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(webSocketChildChannelHandler);
//                    .childHandler(new WebSocketChildChannelHandler());
            System.out.println("server running and waiting for client to connect.");
            Channel channel = bootstrap.bind(8888).sync().channel();
            channel.closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }
}
